<template>
  <div class="shortcut-key" :class="[hide && 'hide', hover && 'shortcut-key-hover', disabled && 'disabled']" @click.stop="onClick">
    <slot>
      <slot name="keyName">
        <div v-if="keyName" class="key-wrap" :style="style">{{ keyName }}</div>
      </slot>
      <slot name="key-title">
        <p v-if="title" class="key-title">{{ title }}</p>
      </slot>
    </slot>
  </div>
</template>

<script setup lang="ts">
  import hotkeys, { HotkeysEvent } from 'hotkeys-js'
  import { computed, onUnmounted } from 'vue'

  export interface ShortcutKeyProps {
    // 标题
    title?: string
    // 快捷键
    keys: string
    // 键名
    keyName?: string
    // 大小
    size?: number
    // 隐藏内容
    hide?: boolean
    // 是否可点击触发
    isClickTrigger?: boolean
    // 是否添加hover
    hover?: boolean
    // 禁用
    disabled?: boolean
    // 数据
    data?: any
  }
  const props = withDefaults(defineProps<ShortcutKeyProps>(), {
    title: '',
    keys: 'Delete',
    keyName: '',
    size: 20,
    hide: false,
    isClickTrigger: true,
    hover: false,
    disabled: false
  })

  const emits = defineEmits<{
    (event: 'trigger', params: ShortcutKeyProps, handler?: HotkeysEvent): void
  }>()

  const onClick = () => {
    if (!props.isClickTrigger) {
      return
    }
    emits('trigger', props)
  }

  const style = computed(() => {
    return {
      width: `${props.size}px`,
      height: `${props.size}px`
    }
  })

  hotkeys(props.keys, function (event, handler) {
    event.preventDefault()
    if (props.disabled) {
      return
    }
    emits('trigger', props, handler)
  })

  onUnmounted(() => {
    hotkeys.unbind(props.keys)
  })
</script>

<style lang="less" scoped>
  .shortcut-key {
    display: flex;
    align-items: center;
    height: 100%;
    gap: 0 8px;
    cursor: pointer;
    color: rgba(17, 22, 31, 0.75);

    &.shortcut-key-hover {
      padding: 4px 8px;
      border-radius: 6px;

      &:hover {
        background: rgba(0, 0, 0, 0.05);
      }
    }

    &.disabled {
      pointer-events: none;
      opacity: 0.5;
    }

    &.hide {
      display: none;
    }

    .key-wrap {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 12px;
      text-align: center;
      border: 1px dashed #d9dadb;
    }

    .key-title {
      font-size: 14px;
    }
  }
</style>
